#include "flowtool.h"
#include "customgraphicsscene.h"
#include "../shape/shape.h"
#include "../flow/noteflow.h"
#include "../flow/arrowflow.h"

FlowSceneTool::FlowSceneTool (CustomGraphicsScene::EditorTool oldtool)
	: _oldtool(oldtool)
{
}

bool FlowSceneTool::activate (CustomGraphicsScene *scene, SceneTool *prev)
{
	SceneTool::activate(scene, prev); // меня терзают смутные сомненья...
	_templine = NULL;
}

bool FlowSceneTool::mousePressEvent (QGraphicsSceneMouseEvent *event)
{
	if (event->button()!=Qt::LeftButton) return true;
	scene()->setSelectionArea(QPainterPath());
	Shape *item = dynamic_cast<Shape *>(scene()->itemAt(event->scenePos()));
	if (item)
	{
		item->setSelected(true);
		_templine = new QGraphicsLineItem(NULL, scene());
		_templine->setLine(QLineF(event->scenePos(), event->scenePos()));
		QPen pen(Qt::gray);
		pen.setStyle(Qt::DotLine);
		_templine->setPen(pen);
	}
	return false;
}

bool FlowSceneTool::mouseMoveEvent (QGraphicsSceneMouseEvent *event)
{
	if (_templine)
	{
		_templine->setLine(QLineF(_templine->line().p1(), event->scenePos()));
		scene()->setSelectionArea(QPainterPath());
		Shape *s;
		_templine->setVisible(false);
		if (s=dynamic_cast<Shape *>(scene()->itemAt(_templine->line().p1())))
			s->setSelected(true);
		if (s=dynamic_cast<Shape *>(scene()->itemAt(_templine->line().p2())))
			s->setSelected(true);
		_templine->setVisible(true);
	}
	return true;
}

Flow *FlowSceneTool::flowExists (Shape *s, Shape *e)
{
	Flow *f;
	foreach(Shape *item, scene()->shapes())
		if (f=dynamic_cast<Flow *>(item))
		{
			if ((f->startShape()==s && f->endShape()==e)
				|| (f->startShape()==e && f->endShape()==s))
				return f;
		}
	return NULL;
}

bool FlowSceneTool::mouseReleaseEvent (QGraphicsSceneMouseEvent *event)
{
	if (event->button()!=Qt::LeftButton) return true;

	if (_templine)
	{
		QPointF p1 = _templine->line().p1();
		QPointF p2 = _templine->line().p2();
		delete _templine; _templine = NULL;

		Shape *item1 = dynamic_cast<Shape *>(scene()->itemAt(p1));
		Shape *item2 = dynamic_cast<Shape *>(scene()->itemAt(p2));
		if (item1 && item2)
		{
			bool done = false;
			scene()->notifyStateChangeByUser();
			if (item1!=item2)
				switch(_oldtool)
				{
					case CustomGraphicsScene::NOTEFLOW:
						if (NoteFlow::canConnect(item1,item2))
							scene()->addShape(new NoteFlow(item1, item2)), done = true;
						break;
					case CustomGraphicsScene::ARROWFLOW:
						if (ArrowFlow::canConnect(item1,item2))
							scene()->addShape(new ArrowFlow(item1, item2)), done = true;
						break;
				}
			if (done)
				scene()->setTool(CustomGraphicsScene::SELECTION); // (!) потом заменить на setCurrentTool!
		}
		scene()->setSelectionArea(QPainterPath());
	}
	return false;
}

bool FlowSceneTool::mouseDoubleClickEvent (QGraphicsSceneMouseEvent *event)
{
	return false;
}
